import React, { useRef, useState, useCallback } from 'react';
import { Button, Space, message } from 'antd';
import { CameraOutlined, RedoOutlined } from '@ant-design/icons';
import Webcam from 'react-webcam';
import './styles.scss';

const WebcamCapture = ({ onCapture }) => {
  const webcamRef = useRef(null);
  const [isCameraReady, setCameraReady] = useState(false);
  const [cameraError, setCameraError] = useState(false);
  const [capturedImage, setCapturedImage] = useState(null);
  const [showCamera, setShowCamera] = useState(true);

  // 设置摄像头配置
  const videoConstraints = {
    width: 400,
    height: 400,
    facingMode: "user" // 使用前置摄像头
  };

  // 拍照
  const capture = useCallback(() => {
    if (webcamRef.current) {
      const imageSrc = webcamRef.current.getScreenshot();
      if (imageSrc) {
        setCapturedImage(imageSrc);
        setShowCamera(false);
        if (onCapture) {
          onCapture(imageSrc);
        }
      }
    }
  }, [webcamRef, onCapture]);

  // 处理摄像头准备就绪
  const handleUserMedia = () => {
    setCameraReady(true);
    setCameraError(false);
  };

  // 处理摄像头错误
  const handleCameraError = () => {
    setCameraReady(false);
    setCameraError(true);
    message.error('无法访问摄像头，请确保摄像头已连接并授予权限。');
  };

  // 重试摄像头连接
  const retryCamera = () => {
    setCameraError(false);
    // 强制重新渲染摄像头组件
    webcamRef.current = null;
    setTimeout(() => {
      setCameraReady(false);
    }, 100);
  };

  // 重新拍照
  const retake = () => {
    setCapturedImage(null);
    setShowCamera(true);
  };

  return (
    <div className="webcam-capture">
      {!cameraError ? (
        <>
          {showCamera ? (
            <>
              <Webcam
                audio={false}
                height={400}
                ref={webcamRef}
                screenshotFormat="image/jpeg"
                width={400}
                videoConstraints={videoConstraints}
                onUserMedia={handleUserMedia}
                onUserMediaError={handleCameraError}
                className="webcam"
              />
              {isCameraReady && (
                <Button 
                  type="primary" 
                  icon={<CameraOutlined />} 
                  onClick={capture}
                  className="capture-button"
                >
                  拍照
                </Button>
              )}
            </>
          ) : (
            <>
              <div className="captured-image-container">
                <img src={capturedImage} alt="已拍照片" className="captured-image" />
              </div>
              <Button 
                icon={<RedoOutlined />} 
                onClick={retake}
                className="retake-button"
              >
                重新拍照
              </Button>
            </>
          )}
        </>
      ) : (
        <div className="camera-error">
          <p>无法访问摄像头</p>
          <Space>
            <Button 
              type="primary" 
              icon={<RedoOutlined />} 
              onClick={retryCamera}
            >
              重试
            </Button>
          </Space>
        </div>
      )}
    </div>
  );
};

export default WebcamCapture; 